package com.sl.camera_demo

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Matrix
import android.media.ExifInterface
import android.util.Log
import io.flutter.plugin.common.MethodChannel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.io.File
import java.io.FileOutputStream
import java.lang.Exception

class BitmapCutUtil(val path: String, val imgRect: CutRect, val borderRect: CutRect, val result: MethodChannel.Result) {
    private var bitmap: Bitmap? = null
    fun initBitmap() {
        bitmap = BitmapFactory.decodeFile(path)
    }

    fun dealBitMap() {
        var exift: ExifInterface? = null
        exift = getExift()
        exift?.run {
            val rotation = getRotation(this)
            val rotationD = when (rotation) {
                ExifInterface.ORIENTATION_ROTATE_90 -> 90
                ExifInterface.ORIENTATION_ROTATE_270 -> 270
                ExifInterface.ORIENTATION_ROTATE_180 -> 180
                else -> 0
            }
            if (rotationD != 0) {
                setBitMapRotation2Zero(rotationD)
            }
            ///裁剪图片
            cutBitMap(rotationD)
            ///压缩图片
            resizeBitMap()
            var job = GlobalScope.launch {
                Log.e("BitmapCutUtil","${bitmap!!.width/bitmap!!.height.toDouble()}")
                ///保存图片
                saveBitMap()
                ///清除缓存
                onDestory()
                launch(Dispatchers.Main) {
                    result.success(path)
                }
            }
        }
    }

    private fun setBitMapRotation2Zero(rotation: Int) {
        var canvasBitMap: Bitmap? = null
        var matrix = Matrix()
        matrix.setRotate(rotation.toFloat(), bitmap!!.width / 2f, bitmap!!.height / 2f)
        canvasBitMap = Bitmap.createBitmap(bitmap!!, 0, 0, bitmap!!.width, bitmap!!.height, matrix, true)

//        } else {
//            Bitmap.createBitmap(bitmap!!, 0, 0, bitmap!!.height, bitmap!!.width, matrix, true)
//        }
        bitmap?.recycle()
        bitmap = canvasBitMap
    }

    private fun getExift(): ExifInterface? {
        var e: ExifInterface? = null
        try {
            e = ExifInterface(path)
        } catch (e: Exception) {

        }
        return e
    }

    private fun saveBitMap() {
        var file = File(path)
        var fo = FileOutputStream(file)
        bitmap!!.compress(Bitmap.CompressFormat.JPEG, 100, fo)
        fo.flush()
        fo.close()
    }

    private fun resizeBitMap() {

    }

    private fun cutBitMap(rotation: Int) {
        var widthRatio = imgRect.width!! / bitmap!!.width
        var heightRatio = imgRect.height!! / bitmap!!.height
        var cutX = (borderRect.startX!! - imgRect.startX!!) / widthRatio
        var cutY = (borderRect.startY!! - imgRect.startY!!) / heightRatio
        var cutWidth = borderRect.width!! / widthRatio
        var cutHeight = borderRect.height!! / heightRatio
        var canvasBitMap: Bitmap? = null

        canvasBitMap = if (rotation == 90 || rotation == 270) {
            var matrix = Matrix()
            matrix.setRotate((-90).toFloat(), bitmap!!.width / 2f, bitmap!!.height / 2f)
            Bitmap.createBitmap(bitmap!!, cutX.toInt(), cutY.toInt(), cutWidth.toInt(), cutHeight.toInt(), matrix, true)
        } else {
            //重算裁剪参数
            widthRatio = imgRect.width!! / bitmap!!.height
            heightRatio = imgRect.height!! / bitmap!!.width
            cutX = (imgRect.width!! - (borderRect.startX!! + borderRect.width!!)) / widthRatio
            cutY = (imgRect.height!! - (borderRect.startY!! + borderRect.height!!)) / heightRatio
            cutWidth = borderRect.height!! / widthRatio
            cutHeight = borderRect.width!! / heightRatio
            Bitmap.createBitmap(bitmap!!, cutY.toInt(), cutX.toInt(), cutWidth.toInt(), cutHeight.toInt())
        }

//        canvasBitMap = if (rotation == 90 || rotation == 270) {
//            Bitmap.createBitmap(bitmap!!, cutX.toInt(), cutY.toInt(), cutWidth.toInt(), cutHeight.toInt())
//        } else {
//
////            Bitmap.createBitmap(bitmap!!,cutY.toInt(),cutX.toInt(),cutHeight.toInt(),cutWidth.toInt())
//        }

        bitmap?.recycle()
        bitmap = canvasBitMap
    }

    private fun getRotation(exift: ExifInterface): Int {
        return exift.getAttributeInt(ExifInterface.TAG_ORIENTATION, -1)
    }

    private fun onDestory() {
        bitmap?.recycle()
        bitmap = null
        System.gc()
    }

}